package dal

import (
	"context"

	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"

	"gorm.io/gorm"
)

// Get buyer storage instance
func GetBuyerDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
	return util.GetDB(ctx, defDB).Model(new(schema.Buyer))
}

// 意向客户表
type Buyer struct {
	DB *gorm.DB
}

// Query buyers from the database based on the provided parameters and options.
func (a *Buyer) Query(ctx context.Context, params schema.BuyerQueryParam, opts ...schema.BuyerQueryOptions) (*schema.BuyerQueryResult, error) {
	var opt schema.BuyerQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	db := GetBuyerDB(ctx, a.DB)
	if v := params.UID; len(v) > 0 {
		db = db.Where("uid = ?", v)
	}
	if v := params.LikeName; len(v) > 0 {
		db = db.Where("name LIKE ?", "%"+v+"%")
	}
	if v := params.LikePhone; len(v) > 0 {
		db = db.Where("phone LIKE ?", "%"+v+"%")
	}
	if v := params.LikeStoreName; len(v) > 0 {
		db = db.Where("store_name LIKE ?", "%"+v+"%")
	}
	if v := params.Status; len(v) > 0 {
		db = db.Where("status = ?", v)
	}

	var list schema.Buyers
	pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	queryResult := &schema.BuyerQueryResult{
		PageResult: pageResult,
		Data:       list,
	}
	return queryResult, nil
}

// Get the specified buyer from the database.
func (a *Buyer) Get(ctx context.Context, id string, opts ...schema.BuyerQueryOptions) (*schema.Buyer, error) {
	var opt schema.BuyerQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}

	item := new(schema.Buyer)
	ok, err := util.FindOne(ctx, GetBuyerDB(ctx, a.DB).Where("id=?", id), opt.QueryOptions, item)
	if err != nil {
		return nil, errors.WithStack(err)
	} else if !ok {
		return nil, nil
	}
	return item, nil
}

// Exist checks if the specified buyer exists in the database.
func (a *Buyer) Exists(ctx context.Context, id string) (bool, error) {
	ok, err := util.Exists(ctx, GetBuyerDB(ctx, a.DB).Where("id=?", id))
	return ok, errors.WithStack(err)
}

// Create a new buyer.
func (a *Buyer) Create(ctx context.Context, item *schema.Buyer) error {
	result := GetBuyerDB(ctx, a.DB).Create(item)
	return errors.WithStack(result.Error)
}

// Update the specified buyer in the database.
func (a *Buyer) Update(ctx context.Context, item *schema.Buyer) error {
	result := GetBuyerDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
	return errors.WithStack(result.Error)
}

// Delete the specified buyer from the database.
func (a *Buyer) Delete(ctx context.Context, id string) error {
	result := GetBuyerDB(ctx, a.DB).Where("id=?", id).Update("status", "disabled")
	return errors.WithStack(result.Error)
}

// Delete the specified buyer from the database.
func (a *Buyer) DeleteStatus(ctx context.Context, id string) error {
	result := GetBuyerDB(ctx, a.DB).Where("id=?", id).Update("status", "disabled")
	return errors.WithStack(result.Error)
}
